using JT808Protocol.Abstracts;
using JT808Protocol.Models;
using System.Collections.Generic;

namespace JT808Protocol.Methods
{
    public class RequestContext
    {
        /// <summary>
        /// 消息处理方式容器
        /// </summary>
        private MsgHandlerContainer _msgHandleContainer;

        /// <summary>
        /// 消息转发器集合
        /// </summary>
        public readonly List<IDataForwarder> Forwarders = new List<IDataForwarder>();

        public RequestContext(MsgHandlerContainer msgHandleContainer)
        {
            _msgHandleContainer = msgHandleContainer;
        }

        /// <summary>
        /// 处理和转发设备请求数据包，并返回平台应答数据包
        /// </summary>
        /// <param name="package">设备数据包</param>
        /// <returns>平台数据包</returns>
        public JT808Package[] Handle(JT808Package package)
        {
            ForwardPackage(package);
            return HandleRequest(package);
        }

        internal void ForwardPackage(JT808Package package)
        {
            foreach (var forwarder in Forwarders)
            {
                forwarder.SendAsync(package);
            }
        }

        internal JT808Package[] HandleRequest(JT808Package package)
        {
            return _msgHandleContainer?.Handle(package);
        }
    }
}